package com.syq.service.impl;

import com.syq.cache.CategoriesCache;
import com.syq.constants.ResultCode;
import com.syq.dao.DeviceMapper;
import com.syq.dao.SysCategoryMapper;
import com.syq.dto.SysDeviceDto;
import com.syq.exceptions.AddException;
import com.syq.exceptions.UpdateException;
import com.syq.pojo.CheckType;
import com.syq.pojo.SysCategory;
import com.syq.pojo.SysDevice;
import com.syq.service.SysDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
public class SysDeviceServiceImpl implements SysDeviceService {
    private DeviceMapper deviceMapper;

    private CategoriesCache categoriesCache;

    @Autowired
    public void setCategoriesCache(CategoriesCache categoriesCache) {
        this.categoriesCache = categoriesCache;
    }

    @Autowired
    public void setDeviceMapper(DeviceMapper deviceMapper) {
        this.deviceMapper = deviceMapper;
    }


    @Override
    public void addDevice(SysDeviceDto sysDeviceDto) {
        Assert.isTrue(!sysDeviceDto.isEmpty(CheckType.ADD),()->{
            throw new AddException("请输入完整数据", ResultCode.DATA_NULL);
        });

        Long categyId = sysDeviceDto.getCategyId();

        SysCategory byId = categoriesCache.getById(categyId);
        Assert.isTrue(byId!=null&&byId.getStatus()==1,()->{
            throw new AddException("分类不存在",ResultCode.CATEGORY_NOT_EXIST);
        });

        deviceMapper.addDevice(sysDeviceDto);
    }

    @Override
    public int update2Sell(String deviceId) {
        Assert.notNull(deviceId,()->{
            throw new UpdateException("主键不符合要求",ResultCode.ID_NOTALLOWED);
        });
        SysDevice byDeviceId = deviceMapper.findByDeviceId(deviceId);
        Assert.notNull(byDeviceId,()->{
            throw new UpdateException("设备不存在",ResultCode.DEVICE_NOT_EXIST);
        });
        Assert.isTrue(byDeviceId.getStatus()==0,()->{
            throw new UpdateException("设备状态不匹配",ResultCode.DEVICE_NOT_EXIST);
        });
        return deviceMapper.update2Sell(deviceId);
    }
}
